from django.contrib.auth import get_user_model

from rest_framework import mixins, viewsets, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler

from .models import MobileVerifyRecord, EmailVerifyRecord
from apps.users.serializers import UserProfileSerializer, MobileVerifyRecordSerializer, EmailVerifyRecordSerializer

User = get_user_model()


class UserProfileViewSet(viewsets.ModelViewSet):
    authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    permission_classes = (IsAuthenticated,)
    
    queryset = User.objects.all().order_by('-first_name')
    serializer_class = UserProfileSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username
        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def get_permissions(self):
        """
        动态权限配置
            1.用户注册时，无权限限制
            2.获取用户详情信息时，须登录
        """
        if self.action in ("retrieve", "list"):
            return [IsAuthenticated()]
        elif self.action == "create":
            return []
        return []

    def get_serializer_class(self):
        """
        动态选择序列化方式
            UserRegSerializer（用户注册），只返回username和mobile，创建一个UserDetailSerializer，显示用户详情
        """
        if self.action == "retrieve":
            return UserDetailSerializer
        elif self.action == "create":
            return UserRegSerializer

        return UserDetailSerializer

    def get_object(self):
        """
        虽然继承了Retrieve可以获取用户详情，获取的是用户id
        重写get_object方法，获取通过用户id解析出的用户对象
        """
        return self.request.user

    def perform_create(self, serializer):
        return serializer.save()


class MobileVerifyRecordViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    queryset = MobileVerifyRecord.objects.all()
    serializer_class = MobileVerifyRecordSerializer


class EmailVerifyRecordViewSet(mixins.CreateModelMixin, viewsets.ModelViewSet):
    queryset = EmailVerifyRecord.objects.all()
    serializer_class = EmailVerifyRecordSerializer
